﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Shop.Intermediate;
using Shop.Core.Configuration;
using Shop.Intermediate.Data;
using Shop.Intermediate.Repository;

namespace Shop.Core
{
    public class BasicDataCore
    {
        private IDataProvider m_dataProvider;
        private IBasicDataRepository m_bdRepository;

        public BasicDataCore()
        {
            this.m_dataProvider = ConfigAccess.CreateDataProvider();
            this.m_bdRepository = m_dataProvider.BasicDataRepository;
        }

        public bool Save(IBasicData entity, ref string message)
        {
            bool result = true;

            IBasicData en;
            en = m_bdRepository.GetEntity(entity.Code);
            if (en!=null)
            {
                result = false;
                message = "存在相同的代码！\\n";
            }
            en = m_bdRepository.GetList(" Name==@0 ", new object[] { entity.Name }).FirstOrDefault();
            if (en != null)
            {
                result = false;
                message = message + "存在相同的名称！";
            }

            if (result == true)
            {
                m_bdRepository.Create(entity);
                m_dataProvider.SubmitChanges();
                message = "添加成功！";
            }
            return result;
        }

        public bool Update(IBasicData entity, ref string message)
        {
            bool result = true;

            IBasicData en;
            en = m_bdRepository.GetList(" Name==@0 && Code!=@1", new object[] { entity.Name, entity.Code }).FirstOrDefault();

            if (en != null)
            {
                result = false;
                message = message + "存在相同的名称！";
            }

            if (result == true)
            {
                m_bdRepository.Update(entity);
                m_dataProvider.SubmitChanges();
                message = "更新成功！";
            }
            return result;
        }

        public IBasicData GetEntity(string code)
        {
            return m_bdRepository.GetEntity(code);
        }

        public IBasicData NewBasicData()
        {
            return m_dataProvider.NewBasicData();
        }

        public IEnumerable<IBasicData> GetList()
        {
            return m_bdRepository.GetList();
        }

        public IEnumerable<IBasicData> GetList(string condition, object[] obj)
        {
            return m_bdRepository.GetList(condition, obj);
        }

        public IEnumerable<IBasicData> GetList(string condition, object[] whereObj, string ordering, object[] orderObj)
        {
            return m_bdRepository.GetList(condition, whereObj, ordering, orderObj);
        }
    }
}
